package cn.turboinfo.fuyang.api.gateway.share.config

import cn.turboinfo.fuyang.api.gateway.share.framework.http.context.ShareRequestContextHolder
import mu.KotlinLogging
import nxcloud.ext.springmvc.automapping.spi.AutoMappingRequestParameterInjector
import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestParameterTypeBinding
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.MethodParameter
import org.springframework.web.context.request.NativeWebRequest

@Configuration
class ShareAutoMappingConfig {

    private val logger = KotlinLogging.logger {}

    /**
     * 企业编码 自动注入
     */
    @Bean
    protected fun shareCompanyScopeAutoMappingRequestParameterInjector(
        autoMappingRequestParameterTypeBinding: AutoMappingRequestParameterTypeBinding,
    ): AutoMappingRequestParameterInjector {
        return object : AutoMappingRequestParameterInjector {
            override fun inject(
                parameterObj: Any,
                parameter: MethodParameter,
                resolvedParameterType: Class<*>,
                webRequest: NativeWebRequest
            ) {
                try {
                    val field = parameterObj::class.java.getDeclaredField("companyId")
                    field.isAccessible = true
                    field.set(parameterObj, ShareRequestContextHolder.current().companyId)
                } catch (e: NoSuchFieldException) {
                    // 忽略传递未知属性的情况
                    logger.debug { "$parameter 未要求 companyId" }
                }
            }

            override fun isSupported(
                parameterObj: Any,
                parameter: MethodParameter,
                resolvedParameterType: Class<*>,
                webRequest: NativeWebRequest
            ): Boolean {
                return ShareRequestContextHolder.exists()
            }
        }
    }
}
